import {AbstractControl, ValidatorFn, Validators} from '@angular/forms';

export class MyValidators extends Validators {
  static rang(min: number, max: number): ValidatorFn {
    return (control: AbstractControl): { [key: string]: any } => {
      const value = control.value;
      let reg = /^(0|[1-9][0-9]*|-[1-9][0-9]*)$/;
      if (!reg.test(value)) {
        return {'rang': {value}}
      }
      const result = control.value as number;
      return !(result >= min && result <= max) ? {'rang': {result}} : null
    };
  }

  static numberRang(min: number, max: number): ValidatorFn {
    return (control: AbstractControl): { [key: string]: any } => {
      const value = control.value;
      let reg = /^(-?\d+)(\.\d+)?$/;
      if (!reg.test(value)) {
        return {'rang': {value}}
      }
      const result = control.value as number;
      return !(result >= min && result <= max) ? {'rang': {result}} : null
    };
  }

  static maxNum(num: number): ValidatorFn {
    return (control: AbstractControl): { [key: string]: any } => {
      const value = control.value;
      if (value >= 65536) {
        return {'maxNum': {value}}
      }
      let reg = /\.\d{3,}$/;
      if (reg.test(value)) {
        return {'maxNum': {value}}
      }
      return null
    };
  }

}
